package com.tour.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.tour.common.Const;
import com.tour.common.ResponseCode;
import com.tour.common.ServerResponse;
import com.tour.dao.ScenicMapper;
import com.tour.dao.TrDescMapper;
import com.tour.dao.TrevalProjectMapper;
import com.tour.pojo.EasyUIDataGridResult;
import com.tour.pojo.Scenic;
import com.tour.pojo.TrDesc;
import com.tour.pojo.TrevalProject;
import com.tour.service.IScenicService;
import com.tour.service.ITrevalProjectService;
import com.tour.util.IDUtils;
import com.tour.vo.TrevalProjectListVo;

/**
 * Created by fivedeath
 */
@Service("iProductService")
public class TrevalProjectServiceImpl implements ITrevalProjectService {

	@Autowired
	private TrevalProjectMapper trevalProjectMapper;

	@Autowired
	private ScenicMapper scenicMapper;
	
	@Resource
	private TrDescMapper trDescMapper;

	@Autowired
	private IScenicService iScenicService;

	// 保存或更新旅游项目
	public ServerResponse saveOrUpdateProject(TrevalProject trevalProject, String desc) {
		if (trevalProject != null) {
			if (StringUtils.isNotBlank(trevalProject.getMainImg())) {
				String[] subImageArray = trevalProject.getMainImg().split(",");
				if (subImageArray.length > 0) {
					trevalProject.setTitleImg(subImageArray[0]);
				}
			}

			if (trevalProject.getTrId() != null) {
				int rowCount = trevalProjectMapper.updateByPrimaryKey(trevalProject);
				if (rowCount > 0) {
					return ServerResponse.createBySuccess("更新旅游项目成功");
				}
				return ServerResponse.createBySuccess("更新旅游项目失败");
			} else {
				//生成id
				Long trId = IDUtils.genItemId();
				trevalProject.setTrId(trId);
				//新建一个景点描述类
				TrDesc trDesc = new TrDesc(trId, new Date(), new Date(), desc);
				int rowCount = trevalProjectMapper.insert(trevalProject);
				int rowCountTd = trDescMapper.insert(trDesc);
				if (rowCount > 0 && rowCountTd > 0) {
					return ServerResponse.createBySuccess("新增旅游项目成功");
				}
				return ServerResponse.createBySuccess("新增旅游项目失败");
			}
		}
		return ServerResponse.createByErrorMessage("新增或更新旅游项目参数不正确");
	}

	// 设置销售状态
	public ServerResponse<String> setStatus(Long projectId, Integer status) {
		 if(projectId == null || status == null){
		 return
		 ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(),ResponseCode.ILLEGAL_ARGUMENT.getDesc());
		 }
		 TrevalProject project = new TrevalProject();
		 project.setTrId(projectId);
		 project.setStatus(status);
		 int rowCount = trevalProjectMapper.updateByPrimaryKeySelective(project);
		 if(rowCount > 0){
		 return ServerResponse.createBySuccess("修改项目状态成功");
		 }
		 return ServerResponse.createByErrorMessage("修改项目状态失败");
	}

	// 管理项目详情
	public ServerResponse<TrevalProject> manageProjectDetail(Long projectId) {
		if (projectId == null) {
			return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(),
					ResponseCode.ILLEGAL_ARGUMENT.getDesc());
		}
		TrevalProject project = trevalProjectMapper.selectByPrimaryKey(projectId);
		if (project == null) {
			return ServerResponse.createByErrorMessage("旅游项目已下架或者删除");
		}
		return ServerResponse.createBySuccess(project);
	}

	// private ProductDetailVo assembleProductDetailVo(Product product){
	// ProductDetailVo productDetailVo = new ProductDetailVo();
	// productDetailVo.setId(product.getId());
	// productDetailVo.setSubtitle(product.getSubtitle());
	// productDetailVo.setPrice(product.getPrice());
	// productDetailVo.setMainImage(product.getMainImage());
	// productDetailVo.setSubImages(product.getSubImages());
	// productDetailVo.setCategoryId(product.getCategoryId());
	// productDetailVo.setDetail(product.getDetail());
	// productDetailVo.setName(product.getName());
	// productDetailVo.setStatus(product.getStatus());
	// productDetailVo.setStock(product.getStock());
	//
	// productDetailVo.setImageHost(PropertiesUtil.getProperty("ftp.server.http.prefix","http://img.happymmall.com/"));
	//
	// Category category =
	// categoryMapper.selectByPrimaryKey(product.getCategoryId());
	// if(category == null){
	// productDetailVo.setParentCategoryId(0);//默认根节点
	// }else{
	// productDetailVo.setParentCategoryId(category.getParentId());
	// }
	//
	// productDetailVo.setCreateTime(DateTimeUtil.dateToStr(product.getCreateTime()));
	// productDetailVo.setUpdateTime(DateTimeUtil.dateToStr(product.getUpdateTime()));
	// return productDetailVo;
	// }

	// 获取旅游项目列表
	public EasyUIDataGridResult getProjectList(int pageNum, int pageSize) {
		// startPage--start
		// 填充自己的sql查询逻辑
		// pageHelper-收尾
		PageHelper.startPage(pageNum, pageSize);
		List<TrevalProject> projectList = trevalProjectMapper.selectList();

//		List<TrevalProjectListVo> trevalProjectListVoList = Lists.newArrayList();
//		for (TrevalProject productItem : projectList) {
//			TrevalProjectListVo projectListVo = assembleProjectListVo(productItem);
//			trevalProjectListVoList.add(projectListVo);
//		}
		PageInfo pageResult = new PageInfo(projectList);
		pageResult.setList(projectList);
		// 创建一个返回值对象
		EasyUIDataGridResult result = new EasyUIDataGridResult();
		result.setRows(projectList);
		// 取分页结果
		PageInfo pageInfo = new PageInfo(projectList);
		// 取总记录数
		long total = pageInfo.getTotal();
		result.setTotal(total);
		return result;
	}

	// 转换成列表视图对象
	private TrevalProjectListVo assembleProjectListVo(TrevalProject project) {
		TrevalProjectListVo trevalProjectListVo = new TrevalProjectListVo();
		trevalProjectListVo.setId(project.getTrId());
		trevalProjectListVo.setProjectType(project.getProjectType());
		trevalProjectListVo.setProjectName(project.getTitle());
//		trevalProjectListVo
//				.setImageHost(PropertiesUtil.getProperty("ftp.server.http.prefix", "http://img.happytour.com/"));
//		trevalProjectListVo.setMainImg(project.getMainImg());
		trevalProjectListVo.setPrice(project.getPrice());
		// trevalProjectListVo.setSubtitle(project.getSubtitle());
		// trevalProjectListVo.setStatus(project.getStatus());
		return trevalProjectListVo;
	}

	// 多条件查询项目信息
	public ServerResponse<PageInfo> searchProject(String title, Long projectId, int pageNum, int pageSize) {
		PageHelper.startPage(pageNum, pageSize);
		if (StringUtils.isNotBlank(title)) {
			title = new StringBuilder().append("%").append(title).append("%").toString();
		}
		List<TrevalProject> projectList = trevalProjectMapper.selectByNameAndProjectId(title, projectId);
		List<TrevalProjectListVo> projectListVoList = Lists.newArrayList();
		for (TrevalProject projectItem : projectList) {
			TrevalProjectListVo projectListVo = assembleProjectListVo(projectItem);
			projectListVoList.add(projectListVo);
		}
		PageInfo pageResult = new PageInfo(projectList);
		pageResult.setList(projectListVoList);
		return ServerResponse.createBySuccess(pageResult);
	}

	// 获取旅游项目详情
	public ServerResponse<TrevalProject> getProjectDetail(Long projectId) {
		if (projectId == null) {
			return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(),
					ResponseCode.ILLEGAL_ARGUMENT.getDesc());
		}
		TrevalProject project = trevalProjectMapper.selectByPrimaryKey(projectId);
		if (project == null) {
			return ServerResponse.createByErrorMessage("该项目已下架或者删除");
		}
		// if(product.getStatus() != Const.ProductStatusEnum.ON_SALE.getCode()){
		// return ServerResponse.createByErrorMessage("产品已下架或者删除");
		// }
		return ServerResponse.createBySuccess(project);
	}

	// 根据关键字查询
	public ServerResponse<PageInfo> getProjectByKeywordCategory(String keyword, Integer toPlaceId, int pageNum,
			int pageSize, String orderBy) {
		if (StringUtils.isBlank(keyword) && toPlaceId == null) {
			return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(),
					ResponseCode.ILLEGAL_ARGUMENT.getDesc());
		}
		List<Integer> scenicIdList = new ArrayList<Integer>();

		if (toPlaceId != null) {
			Scenic scenic = scenicMapper.selectByPrimaryKey(toPlaceId);
			if (scenic == null && StringUtils.isBlank(keyword)) {
				// 没有该分类,并且还没有关键字,这个时候返回一个空的结果集,不报错
				PageHelper.startPage(pageNum, pageSize);
				List<TrevalProjectListVo> projectListVoList = Lists.newArrayList();
				PageInfo pageInfo = new PageInfo(projectListVoList);
				return ServerResponse.createBySuccess(pageInfo);
			}
			scenicIdList = iScenicService.selectScenicAndChildrenById(scenic.getScenicId()).getData();
		}
		if (StringUtils.isNotBlank(keyword)) {
			keyword = new StringBuilder().append("%").append(keyword).append("%").toString();
		}

		PageHelper.startPage(pageNum, pageSize);
		// 排序处理
		if (StringUtils.isNotBlank(orderBy)) {
			if (Const.ProductListOrderBy.PRICE_ASC_DESC.contains(orderBy)) {
				String[] orderByArray = orderBy.split("_");
				PageHelper.orderBy(orderByArray[0] + " " + orderByArray[1]);
			}
		}
		List<TrevalProject> projectList = trevalProjectMapper.selectByNameAndScenicIds(
				StringUtils.isBlank(keyword) ? null : keyword, scenicIdList.size() == 0 ? null : scenicIdList);

		List<TrevalProjectListVo> projectListVoList = Lists.newArrayList();
		for (TrevalProject project : projectList) {
			TrevalProjectListVo projectListVo = assembleProjectListVo(project);
			projectListVoList.add(projectListVo);
		}

		PageInfo pageInfo = new PageInfo(projectList);
		pageInfo.setList(projectListVoList);
		return ServerResponse.createBySuccess(pageInfo);
	}

	/**
	 * 根据id获取项目描述
	 */
	@Override
	public ServerResponse<TrDesc> getTrDescById(Long id) {
		TrDesc trDesc = trDescMapper.selectByPrimaryKey(id);
		if(trDesc!=null)
			return ServerResponse.createBySuccess("查询项目详情成功", trDesc);
		else
			return ServerResponse.createByErrorMessage("查询项目详情错误");
	}

	@Override
	public ServerResponse deleteProject(Long id) {
		if(trevalProjectMapper.deleteByPrimaryKey(id)>0){
			return ServerResponse.createBySuccessMessage("删除项目成功");
		}
		return ServerResponse.createByErrorMessage("删除项目失败");
	}

	@Override
	public ServerResponse getTrCount() {
		return ServerResponse.createBySuccess(trevalProjectMapper.getTrCount());
	}

	/**
	 * 获取集合数据，
	 * @return ServerResponse
	 */
	@Override
	public ServerResponse getTrList(int pageNum, int pageSize) {
		// startPage--start
				// 填充自己的sql查询逻辑
				// pageHelper-收尾
				PageHelper.startPage(pageNum, pageSize);
				List<TrevalProject> projectList = trevalProjectMapper.selectList();

//				List<TrevalProjectListVo> trevalProjectListVoList = Lists.newArrayList();
//				for (TrevalProject productItem : projectList) {
//					TrevalProjectListVo projectListVo = assembleProjectListVo(productItem);
//					trevalProjectListVoList.add(projectListVo);
//				}
				return ServerResponse.createBySuccess("获取集合成功", projectList);
	}
}
